<?php

require_once '../../bootstrap.php';
require_once '../entities/User.php';
require_once '../utils/util.php';
require_once '../utils/mailSender.php';


session_start();

define("REFERAL_PLUS", 1324);
define("DISABLE", 0);
$user = new User();

/*
 * Controlador correspondiente a la clase User.
 */

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   if (isset($_POST['v'])) {
      $v = $_POST['v'];
      if (function_exists($v)) {
         $v($entityManager, $user);
      } else {
         header('Location: ../index.php');
      }
   }
} else {
   header('Location: ../index.php');
}

/*
 * Validate Incoming Form to create a new User on DB.
 */

function validateForm($entityManager, $user) {
   $userErr = '';
   $passErr = '';
   $emailErr = '';
   $walletErr = '';

   if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      if (empty($_POST['user'])) {
         $user = '';
         $userErr = 'User is required.';
      } else {
         $userName = checkInput($_POST['user']);
         $user->setUsuUser($userName);
      }

      if (empty($_POST['pass'])) {
         $pass = '';
         $passErr = 'Pass is required.';
      } else {
         $tmpPass = checkInput($_POST['pass']);
         $pass = md5($tmpPass);
         $user->setUsuPass($pass);
      }

      if (empty($_POST['email'])) {
         $email = '';
         $emailErr = 'eMail is required.';
      } else {
         $email = checkInput($_POST['email']);
         $user->setUsuEmail($email);
      }

      if (empty($_POST['wallet'])) {
         $wallet = '';
         $walletErr = 'Wallet is required';
      } else {
         $wallet = checkInput($_POST['wallet']);
         $user->setUsuWallet($wallet);
      }

      $user->setUsuAuditCreateDate(time()); //Create user date for auditory.
      $hashUser = md5($user->getUsuUser());
      $user->setUsuActivateCode($hashUser);
      $user->setUsuEnable(DISABLE);

      //Si el usuario que se esta registrando viene con un referido,
      //busco el id del usuario que refirio y agrego el id de usuario al referal id del nuevo usuario.
      if (isset($_SESSION['refCode'])) {
         $oldUserId = getUser($entityManager, $_SESSION['refCode']);
         $user->setUsuReferalId($oldUserId);
      }

      if ($userErr == '' && $passErr == '' && $emailErr == '' && $walletErr == '') { //Not error found.
         if (validateUser($entityManager, $user->getUsuUser())) {
            createUser($entityManager, $user);
            // *****************************************
            // Envío del mail para que active la cuenta.
            // *****************************************

            $tmp = md5($user->getUsuUser());
            $data = array("code" => $tmp);
            sendEmail($data, $user->getUsuEmail(), 'activateAccount', 'Welcome to BitOnSoccer');

            echo 'The user was created succesfully.<br />Check your email and enable your account.';

            header('Location: ../index.php');
         } else {
            echo 'The user specificated isn\'t available.';
            header('Location: ../index.php');
         }
      } else { //Errors found and return to register page to correct it.
         echo 'Error en los campos'; //CORREGIR.
         die();
      }
   }
}

/*
 * Create a new User.
 */

function createUser($entityManager, $user) {
   $entityManager->persist($user);
   $entityManager->flush();
   updateUser($entityManager, $user, $user->getUsuId());
}

function updateUser($entityManager, $user, $id) {
   $user = $entityManager->find('User', $id);
   $user->setUsuReferenceCode($user->getUsuId() + REFERAL_PLUS);
   $entityManager->flush();
}

function validateUser($entityManager, $userName) {
   $userData = $entityManager->getRepository('User')->findOneBy(array('usuUser' => $userName));
   if ($userData === NULL) {
//NO EXISTE EL USUARIO
      return TRUE;
   } else {
//EL USUARIO YA EXISTE
      return FALSE;
   }
}

function getUser($entityManager, $refCode) {
   $userData = $entityManager->getRepository('User')->findOneBy(array('usuReferenceCode' => $refCode));
   return $userData->getUsuId();
}
